<?php

namespace App\Services;

use App\Models\ZohoToken;

class CmsService
{
    public function putLeader(){
        $access_token = $this->getToken();
xx($access_token);
        // Check if the lead already exists
        $search_url = 'https://www.zohoapis.com/crm/v3/Leads/search';
        $search_data = array(
            'criteria' => '(Email:equals:lvonfeng@qq.com)'
        );
        $search_headers = array(
            'Authorization: Zoho-oauthtoken ' . $access_token,
            'Content-Type: application/json'
        );
        $search_result = $this->makeCurlRequest($search_url ,'GET' ,$search_data ,$search_headers);
        if($search_result['data']){
            $existing_lead_id = $search_result['data'][0]['id'];
            $update_lead_url = 'https://www.zohoapis.com/crm/v3/Leads/' . $existing_lead_id;
            $lead_data = array(
                'data' => array(
                    array(
                        'id' => $existing_lead_id,
                        'Last_Name' => 'Doe',
                        'Company' => 'ABC Company',
                        'Sales' => 'Francis Lu',
                        'City' => 'aaaaa'
                    )
                )
            );
            $update_lead_headers = array(
                'Authorization: Zoho-oauthtoken ' . $access_token,
                'Content-Type: application/json'
            );
            $update_result = $this->makeCurlRequest($update_lead_url ,'PUT',$lead_data ,$update_lead_headers);
            xx($update_result);

        }else{
            $add_lead_url = 'https://www.zohoapis.com/crm/v2/Leads';
            $data = array(
                'data' => array(
                    array(
                        'First_Name' => 'John',
                        'Last_Name' => 'Doe',
                        'Email' => 'johndoe@example.com',
                        'Company' => 'ABC Company'
                    )
                )
            );
            $headers = array(
                'Authorization: Zoho-oauthtoken ' . $access_token,
                'Content-Type: application/json'
            );
            $result = $this->sendHttp($add_lead_url ,$data ,$headers);
            xx($result);
        }

    }
    /**
     * 获取token  如果失效了就去刷新token
     */
    public function getToken(){
        $token = ZohoToken::first();
        if($token->expires_in > time()){
            //有效期内直接返回不然去刷新token
            return $token->access_token;
        }
        $url = 'https://accounts.zoho.com/oauth/v2/token';
        $data = array(
            'grant_type' => 'refresh_token',
            'client_id' => $token->client_id,
            'client_secret' => $token->client_secret,
            'refresh_token' => $token->refresh_token
        );

        $result = $this->makeCurlRequest($url ,'POST',$data);
        if(@$result['access_token']){
            $token->access_token = $result['access_token'];
            $token->expires_in = intval($result['expires_in']) + time();
            $token->save();
            return $result['access_token'];
        }
        return false;
    }

    /**
     * 首次获取token
     */
    public function firstToken(){
        // 设置Zoho的Self Client信息
        $client_id = '1000.24SN5K304E9FX87LGMJTLZ0PYX8PQG';
        $client_secret = '53f616d38628b2d1a144c00b29ac1dd48c307aea74';
        $redirect_uri = 'https://api.youhomes.com/sdk/callback';

        // 构建获取token的URL
        $url = 'https://accounts.zoho.com/oauth/v2/token';
        $data = array(
            'grant_type' => 'authorization_code',
            'client_id' => $client_id,
            'client_secret' => $client_secret,
            'redirect_uri' => $redirect_uri,
            'code' => '1000.edeb5c3ae121c9b15c97ed182bdc2122.6c788f51b94d2f18c04d1d8884952790'
        );
        $result = $this->makeCurlRequest($url ,'POST' ,$data);
        $token = ZohoToken::first();
        if(!$token){
            $token = new ZohoToken();
        }
        $token->access_token = $result['access_token'];
        $token->refresh_token = $result['refresh_token'];
        $token->expires_in = intval($result['expires_in']) + time();
        $token->api_domain = $result['api_domain'];
        $token->token_type = $result['token_type'];
        $token->client_id = $client_id;
        $token->client_secret = $client_secret;
        $token->save();

    }


    function makeCurlRequest($url, $method = 'GET', $data = array(), $headers = array()) {
        if ($method == 'GET' && !empty($data)) {
            $url = $url . '?' . http_build_query($data);
        }
        $ch = curl_init($url);


        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        if ($method != 'GET') {
            if($method == 'PUT'){
                curl_setopt($ch, CURLOPT_PUT, true); //设置为PUT请求
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
            }elseif($method == 'POST'){
                curl_setopt($ch, CURLOPT_POST, 1);
            }

            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }

        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        $response = curl_exec($ch);
        curl_close($ch);

        return json_decode($response ,true);
    }
}
